import { apiRequest } from '@/utils/api'
import type {
  Sighting,
  SightingFormData,
  ApiResponse,
  PaginationParams
} from '@/types'

/**
 * 线索相关API服务
 */
export const sightingService = {
  /**
   * 提交目击线索（匿名）
   */
  submit: async (data: SightingFormData): Promise<ApiResponse<Sighting>> => {
    const formData = new FormData()

    // 添加线索基本信息
    formData.append('post_id', data.post_id.toString())
    formData.append('sighting_location', data.sighting_location)
    formData.append('sighting_time', data.sighting_time)

    if (data.description) formData.append('description', data.description)
    if (data.photo) formData.append('photo', data.photo)

    return await apiRequest.upload('/sightings', formData)
  },

  /**
   * 获取帖子的线索列表（公开访问）
   */
  getPostSightingsPublic: async (postId: number, params: PaginationParams): Promise<ApiResponse<Sighting[]> & { pagination?: any }> => {
    const queryParams = new URLSearchParams({
      page: params.page.toString(),
      limit: params.limit.toString(),
    })

    return await apiRequest.get(`/sightings/post/${postId}/public?${queryParams}`) as ApiResponse<Sighting[]> & { pagination?: any }
  },

  /**
   * 获取帖子的线索列表（仅帖子作者）
   */
  getPostSightings: async (postId: number, params: PaginationParams): Promise<ApiResponse<Sighting[]> & { pagination?: any }> => {
    const queryParams = new URLSearchParams({
      page: params.page.toString(),
      limit: params.limit.toString(),
    })

    return await apiRequest.get(`/sightings/post/${postId}?${queryParams}`) as ApiResponse<Sighting[]> & { pagination?: any }
  },

  /**
   * 获取线索详情（仅帖子作者）
   */
  getById: async (id: number): Promise<ApiResponse<Sighting>> => {
    return await apiRequest.get(`/sightings/${id}`)
  },

  /**
   * 验证线索
   */
  verify: async (id: number, isVerified: boolean): Promise<ApiResponse> => {
    return await apiRequest.patch(`/sightings/${id}/verify`, { is_verified: isVerified })
  },

  /**
   * 上传线索照片
   */
  uploadPhoto: async (photo: File): Promise<ApiResponse<{ photo_url: string }>> => {
    const formData = new FormData()
    formData.append('photo', photo)

    return await apiRequest.upload('/sightings/upload', formData)
  },
}
